package crp.core.space.domain.services;

import com.google.common.base.Suppliers;
import com.qwlabs.tree.Tree;
import com.qwlabs.tree.TreeNode;
import crp.core.space.domain.models.LocationEntity;

import java.util.List;
import java.util.function.Supplier;

public class LocationPathLoader {
    private final Supplier<List<LocationEntity>> locationSupplier;
    private final Supplier<Tree<LocationEntity>> tree = Suppliers.memoize(this::loadTree);


    public LocationPathLoader(Supplier<List<LocationEntity>> locationSupplier) {
        this.locationSupplier = locationSupplier;
    }

    private Tree<LocationEntity> loadTree() {
        return Tree.toTree(locationSupplier.get(),
                LocationEntity::getId, LocationEntity::getParentId);
    }

    public List<LocationEntity> path(String locationId) {
        return tree.get().findNode(s -> s.getId().equals(locationId))
                .map(TreeNode::getSource)
                .map(location -> tree.get().path(location))
                .orElse(List.of());
    }
}
